﻿using DBUtility;
using DeliveryManage.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Reflection;
using Common;

namespace DeliveryManage.Controllers
{
    public class SystemController : BaseController
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;
        
        #region 角色管理
        public ActionResult RoleManage()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，操作成功！" };
            if (!ChkAdminLevels("RoleManage", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，操作失败！" };
                return View();
            }; //检查权限
            List<DeliveryManage.Model.Sys_Role> list = new List<DeliveryManage.Model.Sys_Role>();
            DeliveryManage.DAL.Sys_Role dal = new DeliveryManage.DAL.Sys_Role();
            list = dal.GetQueryList(0, "", "id asc");
            ViewBag.RoleList = list;
            return View();
        }

        public JsonResult RoleDelete()
        {
            string ids = DTRequest.GetFormString("id");
            //ChkAdminLevel("RoleManage", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            if (!ChkAdminLevels("RoleManage", DTEnums.ActionEnum.Delete.ToString()))
            {
                return Json(new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" }); 
            }; //检查权限
            DeliveryManage.DAL.Sys_Role dal = new DeliveryManage.DAL.Sys_Role();
            string[] id = ids.Split(',');
            for (int i = 0; i < id.Length; i++)
            {
                if (!string.IsNullOrEmpty(id[i]))
                    dal.Delete(Convert.ToInt32(id[i]));
            }
            return Json(new ReturnMsgModel { code = 200, msg = "删除成功！" });
        }
        
        public ActionResult RoleEdit()
        {
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");
            //ChkAdminLevel("RoleManage", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("RoleManage", DTEnums.ActionEnum.Edit.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Sys_Role dal = new DeliveryManage.DAL.Sys_Role();
            DeliveryManage.Model.Sys_Role model = new DeliveryManage.Model.Sys_Role();
            if(_id > 0)
                model = dal.GetModel(_id);

            ViewBag.ActionList = Utils.ActionType();
            ViewBag.AddOrEdit = action;
            ListItemCollection list = new ListItemCollection();
            list.Add(new ListItem("请选择类型...", ""));
            list.Add(new ListItem("超级用户", "1"));
            list.Add(new ListItem("系统用户", "2"));
            ViewData["roletype"] = new SelectList(list,"value","text");
            DeliveryManage.DAL.Sys_Navigation bll = new DeliveryManage.DAL.Sys_Navigation();
            ViewBag.NavList = bll.GetQueryList(0);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult RoleEdit(FormCollection collection)
        {
            bool result = false;
            //ChkAdminLevel("RoleManage", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            if (!ChkAdminLevels("RoleManage", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" });
            }; //检查权限
            string action = collection["AddOrEdit"];
            DeliveryManage.DAL.Sys_Role dal = new DeliveryManage.DAL.Sys_Role();
            DeliveryManage.Model.Sys_Role model = new DeliveryManage.Model.Sys_Role();
            if (collection["role_type"].ToString() == "" || string.IsNullOrEmpty(collection["role_name"])) {
                return Json(new ReturnMsgModel { code = 400, msg = "角色名称不能为空！" });
            }
            model.id = int.Parse(collection["id"]);
            model.role_name = collection["role_name"];
            model.role_type = int.Parse(collection["role_type"]);
            model.is_sys = int.Parse(collection["is_sys"]);

            //获取设置的权限值
            string allaction = collection["cblActionType"];
            if (!string.IsNullOrEmpty(allaction))
            {
                string[] arrary = allaction.Split(',');
                Dictionary<string, string> actiondic = new Dictionary<string, string>();
                foreach (string arr in arrary)
                {
                    if (!string.IsNullOrEmpty(arr)) {
                        string[] par = arr.Replace(" ","").Split('+');
                        if (actiondic.Keys.Contains(par[0]))
                        {
                            actiondic[par[0]] += "," + par[1];
                        }
                        else
                        {
                            actiondic[par[0]] = par[1];
                        }
                    }
                }
                //管理权限
                List<DeliveryManage.Model.Sys_RoleValue> ls = new List<DeliveryManage.Model.Sys_RoleValue>();
                foreach (string item in actiondic.Keys)
                {
                    ls.Add(new DeliveryManage.Model.Sys_RoleValue { role_id = 0, nav_name = item, action_type = actiondic[item].TrimEnd(',') });
                }
                model.user_role_values = ls;
            }
            if (action == "Add")
            {
                if (dal.Add(model) > 0)
                {
                    result = true;
                }
            }
            else {
                result = dal.Update(model);
            }
            if (result)
            {
                return Json(new ReturnMsgModel { code = 200,status=true, msg = "保存成功！" });
            }
            return Json(new ReturnMsgModel { code = 400,status = false, msg = "保存失败！" });
        }
        #endregion
        
        #region 返回用户每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("RatioConfig_page_size", "FxManage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 菜单管理

        #region 菜单管理列表
        public ActionResult SysNavigation()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，操作成功！" };
            if (!ChkAdminLevels("SysNavigation", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，操作失败！" };
                return View();
            }; //检查权限
            List<DeliveryManage.Model.Sys_Navigation> list = new List<DeliveryManage.Model.Sys_Navigation>();
            DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
            list = dal.GetQueryList(0);
            ViewBag.NavigationList = list;

            Dictionary<string, string> typedic = new Dictionary<string, string>();
            typedic.Add("Show", "查看");
            typedic.Add("View", "显示");
            typedic.Add("Add", "增加");
            typedic.Add("Edit", "修改");
            typedic.Add("Delete", "删除");
            typedic.Add("Audit", "审核");
            ViewData["typedic"] = typedic;
            return View();
        }

        #endregion

        #region 删除菜单导航
        public JsonResult SysNavigationDelete()
        {
            if (!ChkAdminLevels("SysNavigation", DTEnums.ActionEnum.Delete.ToString()))
            {
                return Json(new ReturnMsgModel { status = false, code = 400, msg = "您没有执行该操作的权限，操作失败！" });
            }; //检查权限
            string ids = DTRequest.GetFormString("id");
            DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
            string[] id = ids.Split(',');
            for (int i = 0; i < id.Length; i++)
            {
                if (!string.IsNullOrEmpty(id[i]))
                    dal.Delete(Convert.ToInt32(id[i]));
            }
            return Json(new ReturnMsgModel { code = 200, msg = "删除成功！" });
        }

        #endregion

        #region 编辑子级菜单
        public ActionResult SysNavigationEdit()
        {
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，操作成功！" };
            if (!ChkAdminLevels("SysNavigation", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
            DeliveryManage.Model.Sys_Navigation model = new DeliveryManage.Model.Sys_Navigation();
            if (_id > 0)
                model = dal.GetModel(_id);
            if (!string.IsNullOrEmpty(model.action_type))
            {
                string[] action_type = model.action_type.Split(',');
                for (int i = 0; i < action_type.Count(); i++)
                {
                    if (action_type[i].ToString() == "Show")
                    {
                        ViewBag.Show = action_type[i];
                    }
                    else if (action_type[i].ToString() == "View")
                    {
                        ViewBag.View = action_type[i];
                    }
                    else if (action_type[i].ToString() == "Add")
                    {
                        ViewBag.Add = action_type[i];
                    }
                    else if (action_type[i].ToString() == "Edit")
                    {
                        ViewBag.Edit = action_type[i];
                    }
                    else if (action_type[i].ToString() == "Delete")
                    {
                        ViewBag.Delete = action_type[i];
                    }
                    else if (action_type[i].ToString() == "Audit")
                    {
                        ViewBag.Audit = action_type[i];
                    }
                }
            }

            List<DeliveryManage.Model.Sys_Navigation> parentlist = dal.GetParentQueryList(string.Format("parent_id={0}",0));
            ListItemCollection parentitem = new ListItemCollection(); 
            parentitem.Add(new ListItem("请选择父级菜单...", ""));
            foreach (var item in parentlist)
            {
                parentitem.Add(new ListItem(item.title, item.id.ToString()));
            }
            ViewData["parentlist"] = new SelectList(parentitem, "value", "text");
            ViewBag.AddOrEdit = action;
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SysNavigationEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                string action = collection["AddOrEdit"];
                if (!ChkAdminLevels("SysNavigation", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！" });
                }; //检查权限
                DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
                DeliveryManage.Model.Sys_Navigation model = new DeliveryManage.Model.Sys_Navigation();
                if ((action == "Edit" && collection["id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["name"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入视图名称！" });
                }
                if (string.IsNullOrEmpty(collection["parent_id"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择父级菜单！" });
                }
                DeliveryManage.Model.Sys_Navigation modelparent = dal.GetModel(int.Parse(collection["parent_id"]));
                if (modelparent == null)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请选择父级菜单！" });
                }
                if (string.IsNullOrEmpty(collection["sub_title"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入下级菜单！" });
                }
                string action_type = "";
                if (collection["Show"] != null)
                {
                    action_type = "Show,";
                }
                if (collection["View"] != null)
                {
                    action_type += "View,";
                }
                if (collection["Add"] != null)
                {
                    action_type += "Add,";
                }
                if (collection["Edit"] != null)
                {
                    action_type += "Edit,";
                }
                if (collection["Delete"] != null)
                {
                    action_type += "Delete,";
                }
                if (collection["Audit"] != null)
                {
                    action_type += "Audit,";
                }
                action_type = action_type.TrimEnd(',');

                model.id = int.Parse(collection["id"]);
                model.name = collection["name"];
                model.parent_id = int.Parse(collection["parent_id"]);
                model.title = collection["sub_title"];
                model.sub_title = collection["sub_title"];
                model.link_url = collection["link_url"];
                model.sort_id = int.Parse(collection["sort_id"]);
                model.action_type =action_type;
                model.is_lock = int.Parse(collection["is_lock"]);
                model.icon = "layui-icon-right";

                if (action == "Add")
                {
                    if (dal.Add(model) > 0)
                    {
                        result = true;
                    }
                }
                else
                {
                    result = dal.Update(model);
                }
                if (result)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
        }
        #endregion

        #region 编辑父级菜单
        public ActionResult SysParentEdit()
        {
            int _id = DTRequest.GetQueryInt("id");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，操作成功！" };
            if (!ChkAdminLevels("SysNavigation", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
            DeliveryManage.Model.Sys_Navigation model = new DeliveryManage.Model.Sys_Navigation();
            if (_id > 0)
                model = dal.GetModel(_id);
            if (!string.IsNullOrEmpty(model.action_type))
            {
                string[] action_type = model.action_type.Split(',');
                for (int i = 0; i < action_type.Count(); i++)
                {
                    if (action_type[i].ToString() == "Show")
                    {
                        ViewBag.Show = action_type[i];
                    }
                }
            }
            
            ViewBag.AddOrEdit = action;
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SysParentEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                string action = collection["AddOrEdit"];
                if (!ChkAdminLevels("SysNavigation", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！" });
                }; //检查权限
                DeliveryManage.DAL.Sys_Navigation dal = new DeliveryManage.DAL.Sys_Navigation();
                DeliveryManage.Model.Sys_Navigation model = new DeliveryManage.Model.Sys_Navigation();
                if ((action == "Edit" && collection["id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["name"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入视图名称！" });
                }
                if (string.IsNullOrEmpty(collection["title"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入父级菜单！" });
                }
                if (string.IsNullOrEmpty(collection["icon"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入当前菜单的Icon图标代码！" });
                }
                string action_type = "";
                if (collection["Show"] != null)
                {
                    action_type = "Show,";
                }
                action_type = action_type.TrimEnd(',');

                model.id = int.Parse(collection["id"]);
                model.name = collection["name"];
                model.parent_id = 0;
                model.title = collection["title"];
                model.sub_title = collection["title"];
                model.link_url = "";
                model.sort_id = int.Parse(collection["sort_id"]);
                model.action_type = action_type;
                model.is_lock = int.Parse(collection["is_lock"]);
                model.icon = collection["icon"];

                if (action == "Add")
                {
                    if (dal.Add(model) > 0)
                    {
                        result = true;
                    }
                }
                else
                {
                    result = dal.Update(model);
                }
                if (result)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
        }
        #endregion
        #endregion
        
        #region 系统配置
        public ActionResult SystemConfig()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许查看该页面的权限，操作成功！" };
            if (!ChkAdminLevels("SystemConfig", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有查看该页面的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.Model.Sys_Config sysmodel = new DeliveryManage.Model.Sys_Config();
            DeliveryManage.DAL.Sys_Config sysdal = new DeliveryManage.DAL.Sys_Config();
            sysmodel = sysdal.loadConfig();
            int layid = DTRequest.GetQueryInt("layid",2);
            ViewBag.layid = layid;
            return View(sysmodel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SystemConfigEdit(FormCollection collection)
        {
            bool result = false;
            if (!ChkAdminLevels("SystemConfig", DTEnums.ActionEnum.Edit.ToString()))
            {
                return Json(new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" });
            }; //检查权限

            DeliveryManage.DAL.Sys_Config dal = new DeliveryManage.DAL.Sys_Config();
            DeliveryManage.Model.Sys_Config model = dal.loadConfig();

            #region 数据安防
            if (string.IsNullOrEmpty(collection["notsubmit_recording_count"]) || int.Parse(collection["notsubmit_recording_count"]) < 0) 
            {
                return Json(new ReturnMsgModel { code = 400, msg = "请输入未提交录音文件次数！" });
            }
            #endregion

            model.email_host = collection["email_host"];
            model.email_port = int.Parse(collection["email_port"]);
            model.email_send_adress = collection["email_send_adress"];
            model.email_send_pwd = collection["email_send_pwd"];
            model.email_send_user = collection["email_send_user"];
            model.email_send_username = collection["email_send_username"];
            model.email_enable_ssl = bool.Parse(collection["email_enable_ssl"]);
            model.email_enable_ssl = bool.Parse(collection["email_enable_ssl"]);

            result = dal.saveConifg(model);
            if (result)
            {
                MvcApplication.SysConfig = model;
                return Json(new ReturnMsgModel { code = 200, msg = "保存成功！" });
            }
            return Json(new ReturnMsgModel { code = 400, msg = "保存失败！" });
        }
        #endregion

        #region 业绩提成规则设置
        public ActionResult SalaryCalcFuncation()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("SalaryCalcFuncation", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            List<DeliveryManage.Model.Sys_PerformanceRules> list = new List<DeliveryManage.Model.Sys_PerformanceRules>();
            DeliveryManage.DAL.Sys_PerformanceRules dal = new DeliveryManage.DAL.Sys_PerformanceRules();
            list = dal.GetQueryList();
            ViewBag.RulesList = list;
            return View();
        }

        /// <summary>
        /// 新增或编辑规则
        /// </summary>
        /// <returns></returns>
        public ActionResult SalaryRulesAdd()
        {
            string _name = DTRequest.GetQueryString("name");
            string action = DTRequest.GetQueryString("action");
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, status = true, msg = "允许执行该操作的权限，操作成功！" };
            if (!ChkAdminLevels("SalaryCalcFuncation", GetAddOrEdit(action)))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, status = false, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            List<DeliveryManage.Model.Sys_PerformanceRules> list = new List<DeliveryManage.Model.Sys_PerformanceRules>();
            DeliveryManage.DAL.Sys_PerformanceRules  dal= new DeliveryManage.DAL.Sys_PerformanceRules();
            if (!string.IsNullOrEmpty(_name))
            {
                list = dal.GetSalaryRules(_name);
            }
            ViewBag.AddOrEdit = action;
            ViewBag.RulesList = list;
            DeliveryManage.Model.Sys_PerformanceRules defaultModel = new Model.Sys_PerformanceRules();
            if (list != null && list.Count > 0) {
                defaultModel = list[0];
            }
            return View(defaultModel);
        }
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SalaryCalcRulesToAdd(FormCollection collection)
        {
            try
            {
                bool result = false;
                string action = collection["AddOrEdit"];

                #region 数据安防
                if (!ChkAdminLevels("SalaryCalcFuncation", GetAddOrEdit(action)))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "您没有执行该操作的权限，操作失败！！" });
                }; //检查权限
                if ((action == "edit" && collection["Id"] == "0"))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
                }
                if (string.IsNullOrEmpty(collection["Name"]))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请填写规则名字！" });
                }
                #endregion
                DeliveryManage.DAL.Sys_PerformanceRules dal = new DAL.Sys_PerformanceRules();
                #region 数据存储
                if (action == "Edit")
                {
                    //编辑的时候先删除原来的规则
                    string excuteSQl = string.Format("delete Sys_PerformanceRules where Name = (select Name from Sys_PerformanceRules where Id={0}) ", collection["Id"]);
                    DbHelperSQL.ExecuteSql(excuteSQl);
                }

                DeliveryManage.Model.Sys_PerformanceRules model = new Model.Sys_PerformanceRules();
                model.Name = collection["Name"];
                model.ToType = bool.Parse(collection["ToType"]) ? 1 : 0;
                model.IsEnlabe = bool.Parse(collection["IsEnlabe"]);
                string rulesString = collection["RulesString"];
                string[] rulesArr = rulesString.Split(',');
                if (rulesArr.Length > 0)
                {
                    foreach (string rule in rulesArr)
                    {
                        if (!string.IsNullOrEmpty(rule))
                        {
                            string[] ruleInfo = rule.TrimEnd('-').Split('-');
                            if (ruleInfo.Length > 0)
                            {
                                model.MinLimit = decimal.Parse(ruleInfo[0]);
                                model.MaxLimit = decimal.Parse(ruleInfo[1]);
                                model.CommRatio = int.Parse(ruleInfo[2]);
                                dal.Add(model);
                            }
                        }
                    }
                    result = true;
                }

                #endregion
                if (result == true)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" + a });
            }
        }
        #endregion
    }
}